﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Naruto.Subscribe;
using Naruto.TaskManagement.Entitys.Const;
using Naruto.TaskManagement.Entitys.DTO;
using Naruto.TaskManagement.Entitys.Enums;
using Naruto.TaskManagement.Entitys.Models;
using Naruto.TaskManagement.Entitys.VM;
using Naruto.TaskManagement.Infrastructure;
using Naruto.TaskManagement.Infrastructure.Interface;
using Naruto.TaskManagement.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Naruto.TaskManagement.Application.Subscribe
{
    /// <summary>
    /// 任务的订阅处理
    /// </summary>
    public class TaskSubscribe : ISubscribe
    {
        private readonly IServiceProvider serviceProvider;


        private readonly ILogger logger;

        private readonly IConfiguration configuration;

        public TaskSubscribe(ILogger<TaskSubscribe> _logger, IServiceProvider _serviceProvider, IConfiguration _configuration)
        {
            logger = _logger;
            serviceProvider = _serviceProvider;
            configuration = _configuration;
        }
        [Subscribe(name: ConstObject.SendTaskEmailSubscribeKey)]
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <returns></returns>
        public async Task SendEmail(TaskSendEmailDTO info)
        {
            logger.LogInformation("开始处理订阅的邮件发送服务");
            //获取服务
            using var scopePrivoder = serviceProvider.CreateScope();
            var taskRecordRepository = scopePrivoder.ServiceProvider.GetRequiredService<ITaskRecordRepository>();
            var userRepository = scopePrivoder.ServiceProvider.GetRequiredService<IUserRepository>();
            var email = scopePrivoder.ServiceProvider.GetRequiredService<IEmail>();
            //发送的邮箱的集合
            var sendEmailList = new List<string>();

            //获取用户的邮箱
            if (!info.AppointUser.IsNullEmpty())
            {
                var userEmail = await userRepository.GetEmailByUserName(info.AppointUser);

                if (userEmail.IsNullEmpty())
                {
                    return;
                }
                sendEmailList.Add(userEmail);
            }

            //获取任务记录
            var taskRecordInfo = await taskRecordRepository.GetAllById(info.Id);
            if (taskRecordInfo == null)
            {
                return;
            }
            //验证是否有发件人信息
            if (sendEmailList.Count <= 0)
            {
                //获取创建人的组织id
                var organizationId = await userRepository.GetUserOrganizationId(taskRecordInfo.CreateUser);
                if (organizationId.IsNullEmpty())
                {
                    return;
                }
                //获取当前组织下的邮箱
                sendEmailList = await userRepository.GetEmailByOrganizationId(organizationId);
            }
            //构建发送的内容
            var html = BuildContent(taskRecordInfo);
            await email.SendEmailAsync(sendEmailList, info.Title, "", html.ToString());
        }

        /// <summary>
        /// 构建内容
        /// </summary>
        /// <param name="taskRecordInfo"></param>
        /// <returns></returns>
        private string BuildContent(TaskRecordGetAllByIdViewModel taskRecordInfo)
        {
            var html = new StringBuilder();
            html.Append($"<div><label>　　日期：</label>{taskRecordInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")}</div>");
            html.Append($"<div><label>　　标题：</label>{taskRecordInfo.Title}</div>");
            html.Append($"<div><label>　　内容：</label>{taskRecordInfo.Description}</div>");
            html.Append($"<div><label>　　状态：</label>{Enum.GetName(typeof(TaskRecordStatusEnum), taskRecordInfo.Status)}</div>");
            html.Append($"<div><label>重要级别：</label>{taskRecordInfo.Level}</div>");
            html.Append($"<div><label>截止日期：</label>{taskRecordInfo.EndDate.ToString("yyyy-MM-dd")}</div>");
            html.Append($"<div><label>　创建人：</label>{taskRecordInfo.CreateUser}</div>");
            html.Append($"<div><label>创建时间：</label>{taskRecordInfo.CreateTime}</div>");
            if (taskRecordInfo.Status != (int)TaskRecordStatusEnum.Pending)
            {
                html.Append($"<div><label>　操作人：</label>{taskRecordInfo.OperationUser}</div>");
                html.Append($"<div><label>操作时间：</label>{taskRecordInfo.OperationTime.ToString("yyyy-MM-dd HH:mm:ss")}</div>");
                html.Append($"<div><label>备注信息：</label>{taskRecordInfo.Remark}</div>");
            }
            html.Append($"<div style=\"margin-left:5px;margin-top:5px\"><a href='{configuration.GetValue<string>("TaskDetailUrl")}/{taskRecordInfo.Id}'>点我前往</a></div>");

            return html.ToString();
        }
    }
}
